package red.uec.controller.advice;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import red.uec.exception.BusinessException;
import red.uec.model.RestfulResponse;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestControllerAdvice(basePackages={"red.uec.controller"})
@Component
public class ExceptionHandleAdvice /*extends ResponseEntityExceptionHandler*/ {
    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandleAdvice.class);

    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        return new MethodValidationPostProcessor();
    }

    @ExceptionHandler(BusinessException.class)
    public Object handleException(HttpServletRequest request, BusinessException exception) {
        logger.error(exception.getMessage(), exception);
        return new RestfulResponse().fail(exception.getMessage());
    }

    @ExceptionHandler(BindException.class)
    public Object handleException(BindException exception) {
        if(null == exception){
            return new RestfulResponse().unknown();
        }
        logger.error(exception.getMessage(), exception);

        BindingResult bindingResult = exception.getBindingResult();
        if(null == bindingResult){
            logger.warn("'bindingResult' is null.");
            return new RestfulResponse().unknown();
        }

        List<ObjectError> errorList = bindingResult.getAllErrors();
        if(null == errorList || errorList.isEmpty()){
            logger.warn("'errorList' is null or empty.");
            return new RestfulResponse().unknown();
        }

        ObjectError error = errorList.get(0);
        if(null == error){
            logger.warn("'error' is null.");
            return new RestfulResponse().unknown();
        }

        return new RestfulResponse().fail(error.getDefaultMessage());
    }

    @ExceptionHandler(Exception.class)
    public Object handleException(HttpServletRequest request, Exception exception) {
        logger.error(exception.getMessage(), exception);
        return new RestfulResponse().fail();
    }
}
